package kerjodando.vincent;

import java.util.Hashtable;
import java.util.StringTokenizer;

/**
 * @author Vincent.Zhu(zhu1230@gmail.com)
 * 
 */
public class Utils {
	/**
	 * @param s
	 * @return
	 */
	public static Hashtable parseQueryString(String s) {

		if (s == null) {
			throw new IllegalArgumentException();
		}
		Hashtable ht = new Hashtable();
		StringBuffer sb = new StringBuffer();
		String key;
		for (StringTokenizer st = new StringTokenizer(s, "&"); st
				.hasMoreTokens(); ) {

			String pair = st.nextToken();
			int pos = pair.indexOf('=');
			if (pos == -1) {
				throw new IllegalArgumentException();
			}
			System.out.println();
			key = Utils.parseName(pair.substring(0, pos), sb);
			String val = Utils.parseName(
					pair.substring(pos + 1, pair.length()), sb);
			System.out.println("key=>" + key + "val=>" + val);
			String valArray[] = null;
			if (ht.containsKey(key)) {
				String[] oldVals = (String[]) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++) {
					valArray = oldVals;
				}

				valArray[oldVals.length] = val;
			} else {
				valArray = new String[1];
				valArray[0] = val;
			}
			ht.put(key, valArray);
		}

		return ht;
	}

	private static String parseName(String s, StringBuffer sb) {
		sb.setLength(0);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case 43: // '+'
				sb.append(' ');
				break;

			case 37: // '%'
				try {
					sb.append((char) Integer.parseInt(
							s.substring(i + 1, i + 3), 16));
					i += 2;
					break;
				} catch (NumberFormatException e) {
					throw new IllegalArgumentException();
				} catch (StringIndexOutOfBoundsException e) {
					String rest = s.substring(i);
					sb.append(rest);
					if (rest.length() == 2) {
						i++;
					}
				}
				break;

			default:
				sb.append(c);
				break;
			}
		}

		return sb.toString();
	}

}
